<?php
/**
 *
 */

namespace App\Http\Controllers\Common;

use App\Http\Controllers\ApiController;

use App\Http\Requests\Common\YouzanOrderStoreRequest;
use App\Models\Customer\DeviceAccount;
use App\Models\Order;
use App\Models\Panx\Product;
use App\Services\Youzan\OrderService;

class YouzanOrderController extends ApiController
{
    const ROUTES = [
        'redirectUrl' => 'redirect.youzan.order.url'
    ];

    protected $orderService;

    public function __construct(OrderService $orderService)
    {
        $this->orderService = $orderService;
    }

    /**
     * @param YouzanOrderStoreRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \App\Exceptions\ApiAbstractException
     * @throws \Throwable
     */
    public function redirectUrl(YouzanOrderStoreRequest $request)
    {
        /** @var Product $product */
        $product = (new Product)
            ->filterHasYouzan(Product::YOUZAN_PRODUCT)
            ->find($request->product_id);
            $this->checkItemExist($product, 'product');

        if ($product->store && $product->store->youzanAuthorizer) {
            $youzanAuthorizer = $product->store->youzanAuthorizer;
        } else {
            $youzanAuthorizer = $product->customer->youzanAuthorizer ?? null; // 商家被取消有赞权限
        }
            $this->checkIsTrue($youzanAuthorizer, trans('admin.no_auth_to_youzan'));

        $msg = $this->getSourceMsg($request, $product);
        $trade_params = $this->getCreateOrderParams($request, $msg, $youzanAuthorizer, $product);
        $trade_bill = $this->orderService->createOrder($youzanAuthorizer, $trade_params);

        return redirect('http://' . $trade_bill['url']);
    }

    /**
     * @param YouzanOrderStoreRequest $request
     * @param Product $product
     * @return array
     * @throws \Exception
     */
    private function getSourceMsg($request, Product $product): array
    {
        $dev_acnt = (new DeviceAccount)->find($request->device_account_id);
            $this->checkItemExist($dev_acnt, 'device account');

        $msg = [
            'type'              => Order::MIRROR_APP_ORDER_TYPE,
            'product_id'        => $product->id,
            'customer_id'       => $product->customer_id,
            'product_belong_to' => $product->store_id
                ? Order::PRODUCT_BELONG_TO_STORE
                : Order::PRODUCT_BELONG_TO_CUSTOMER , // 商品属于谁，1：客户，2：店铺

            // 生成订单的 buyer message 中保存商品的图片与名称，防止商品被删除？
            'product_thumb_url' => $product->thumbImage->key ?? null,
            'product_title'     => $product->title,

            'device_account_id' => $request->device_account_id,
            // 这里不能用 product, 产品可能存在 store_id 是 0 的情况
            'store_id'          => $dev_acnt->store_id,
        ];

        return $msg;
    }

    /**
     * 参数 message 商品如果设置了留言格式，得按照设置的留言顺序传值
     * 参数 sku_id 在商品设置了规格之后一定得传参数跟值
     *
     * @see Mock::message()
     * @see Mock::skus()
     *
     * @param YouzanOrderStoreRequest $request
     * @param $msg
     * @param $youzanAuthorizer
     * @param $product
     * @return array
     */
    private function getCreateOrderParams(YouzanOrderStoreRequest $request, $msg, $youzanAuthorizer, $product): array
    {
        $params = [
            'item_id'    => $product->youzan_item_id,
            'source'     => json_encode([$msg]),
            'order_type' => 0,
            'num'        => $request->num ?: 1,
            'kdt_id'     => $youzanAuthorizer->youzan_store_id,
            'message'    => json_encode([$msg]), // message 一定要是json
        ];
        return $params;
    }

    public static function routeRedirectUrl(int $prod_id, int $dev_acnt_id): string
    {
        $url = route(self::ROUTES['redirectUrl'],[
            'device_account_id' => $dev_acnt_id,
            'product_id' => $prod_id,
            'num' => 1, // 目前只能购买一个
        ]);

        return $url;
    }
}
